package cn.interestingshop.dao.impl;

import cn.interestingshop.dao.BaseDao;
import cn.interestingshop.dao.OrderInfoDao;
import cn.interestingshop.entity.BaseOrder;
import cn.interestingshop.entity.OrderInfo;
import cn.interestingshop.vo.OrderInfoVo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OrderInfoDaoImpl extends BaseDao implements OrderInfoDao {
    @Override
    public List<OrderInfoVo> selectAll(int baseOrderId) {
        List<OrderInfoVo> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //1. 加载驱动
            //2. 获取连接对象
            conn = getConnection();
            //3. 定义sql语句
            String sql = "SELECT goods_name,file_name,buy_num,amount FROM `t_order_info` a,t_goods b where a.goods_id=b.id and a.base_order_id=?";
            //4. 创建执行对象
            ps = conn.prepareStatement(sql);
            //5. 填充参数
            ps.setInt(1, baseOrderId);
            //6. 执行sql语句
            rs = ps.executeQuery();
            //7. 分析返回结果
            while (rs.next()) {
                OrderInfoVo orderInfoVo = new OrderInfoVo();
                orderInfoVo.setGoodsName(rs.getString("goods_name"));
                orderInfoVo.setFileName(rs.getString("file_name"));
                orderInfoVo.setBuyNum(rs.getInt("buy_num"));
                orderInfoVo.setAmount(rs.getFloat("amount"));
                list.add(orderInfoVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //8.释放资源关闭连接
            closeAll(rs, ps, conn);
        }
        return list;
    }

    @Override
    public int insert(OrderInfo orderInfo) {
        String sql="INSERT INTO `interesting_shop_db`.`t_order_info`(`base_order_id`, `goods_id`, `buy_num`, `amount`) " +
                "VALUES (?, ?, ?, ?)";
        return executeUpdate(sql,new Object[]{
                orderInfo.getBaseOrderId(),
                orderInfo.getGoodsId(),
                orderInfo.getBuyNum(),
                orderInfo.getAmount()
        });
    }
}
